import { 
  generateProblemList, 
  generateProblemDetail,
  getSubmissions,
  getSubmissionsDetail
} from './data/problems';
import { 
    generateHomeData 
} from './data/home';
import {
    getSessions,
    getSessionMessages,
    loadMoreMessages,
    getFriends,
    userSessionMap,
    StaticSessions
} from './data/chat';
import { 
  verificationCodes,
  users,
  avatar_female,
  avatar_male,
  userStats,
  updateUsername,
  updateAvatar,
  changePassword,
  changePasswordByEmail
} from './data/user';
import {
  generateBlogList,
  getBlogDetail,
  submitLike,
  submitComment,
  getSubComments,
  findBlogById
} from './data/blog';


const userData = {
  verificationCodes,
  users
};
import { problem, blog, user, chat, home } from '../api/protobuf-loader.js';

let following = false;
let followers = false;


// 模拟API响应
export const mockResponses = {
  // 统一题目列表接口
  '/user/problems': async (config) => {
    const request = problem.UserProblemListRequest.deserializeBinary(config.data);
    const email = request.getEmail();
    const page = request.getPage();
    const pageSize = request.getPageSize();
    const type = request.getSolved() ? 1: 2;
    const { problems } = generateProblemList(email, type, page, pageSize);
    // problems.forEach(item =>{
    //     item.setSolved(type);
    // });
    
    const response = new problem.UserProblemListResponse();
    response.setProblemsList(problems);
    response.setSuccess(true);
    response.setMessage("获取题目列表成功");
    
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/chat/load_more_messages': async (requestData) => {
    const request = chat.LoadMoreMessagesRequest.deserializeBinary(requestData.data);
    const sessionId = request.getSessionId();
    const lastMessageId = request.getLastMessageId();
    const pageSize = request.getPageSize();
    const {messages, has_more, total} = await loadMoreMessages(sessionId, lastMessageId, pageSize);
    const response = new chat.LoadMoreMessagesResponse();
    messages.forEach(message => {
      const messageProto = new chat.Message();
      messageProto.setMessageId(message.id);
      messageProto.setSessionId(message.session_id);
      messageProto.setFromId(message.from_id);
      messageProto.setSendAt(message.send_at);
      messageProto.setType(message.type);
      if (message.type === 'text') {
        messageProto.setText(message.text);
      } else if (message.type === 'image') {
        const imageProto = new chat.ImageInfo();
        imageProto.setId(message.image.id);
        imageProto.setPath(message.image.path);
        messageProto.setImage(imageProto);
      }
      response.addMessages(messageProto);
    });
    response.setHasMore(has_more);
    response.setTotal(total);
    response.setSuccess(true);
    response.setMessage("请求成功");
    console.log('loadMoreMessages response', response.toObject())
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/home/data': async (requestData) => {
    // 用email作为token信息,用token信息找到这个用户，
    let email = '';
    const token = requestData.headers.Authorization || requestData.headers.authorization;
    if (token){
        const foundUser = users.find(u => u.token === token);
        // 拿到要获取的用户的email
        email = foundUser.email;
    }
    const responseData = generateHomeData(email);
    return {
      data: responseData,
      status: 200,
      statusText: 'OK',
      headers: {
        'Content-Type': 'application/x-protobuf',
        'X-Mock-Request': 'true'
      }
    };
  },
  '/user/send-code': async (data) => {
    // 处理protobuf请求数据
      const request = user.VerificationCodeRequest.deserializeBinary(data.data)

    if (!request.getEmail()) throw new Error('缺少邮箱参数');
    
    const code = "123456";
    console.log(`Mock验证码发送到 ${request.getEmail()}: ${code}`);

    const response = new user.VerificationCodeResponse();
    response.setSuccess(true);
    response.setMessage('验证码发送成功');

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {
        'Content-Type': 'application/x-protobuf',
        'X-Mock-Request': 'true'
      }
    };
  },

  '/user/login': async (requestData) => {
    // 处理protobuf请求数据
    const request = user.LoginRequest.deserializeBinary(requestData.data);
    const foundUser = userData.users.find(u => u.email === request.getEmail() && u.password === request.getPassword());
    if (!foundUser) {
      const response = new user.LoginResponse();
      response.setSuccess(false);
      response.setMessage('用户名或密码错误');
      
      return {
        data: response.serializeBinary(),
        status: 401,
        statusText: 'Unauthorized',
        headers: {}
      };
    }
    const userStat = userStats.find(it => it.email === foundUser.email);
    if (!userStat) {
      throw new Error('找不到用户统计数据');
    }
    // 设置token信息
    let index = userData.users.findIndex(u => u.email === foundUser.email);
    userData.users[index].token = foundUser.email;

    const response = new user.LoginResponse();
    response.setSuccess(true);
    response.setMessage('登录成功');
    response.setToken(foundUser.email);

    const stats = new user.UserStats();
    stats.setEmail(foundUser.email);
    stats.setAvatar(foundUser.avatar);
    stats.setName(foundUser.username);
    stats.setSolvedCount(userStat.solvedCount);
    stats.setTotalProblems(userStat.totalProblems);
    stats.setSolvedProblemsList(userStat.solvedProblems);
    response.setStats(stats);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/user/code-login': async (data) => {
    // 处理protobuf请求数据
      const request = user.CodeLoginRequest.deserializeBinary(data.data);
    const code = request.getCode();

    // 验证码检查
    if ("123456" !== code) {
      const response = new user.LoginResponse();
      response.setSuccess(false);
      response.setMessage('验证码错误');
      
      return {
        data: response.serializeBinary(),
        status: 401,
        statusText: 'Unauthorized',
        headers: {}
      };
    }

    const foundUser = userData.users.find(u => u.email === request.getEmail());
    if (!foundUser) {
      const response = new user.LoginResponse();
      response.setSuccess(false);
      response.setMessage('用户不存在');
      
      return {
        data: response.serializeBinary(),
        status: 404,
        statusText: 'Not Found',
        headers: {}
      };
    }

    const userStat = userStats.find(it => it.email === foundUser.email);
    if (!userStat) {
      throw new Error('找不到用户统计数据');
    }
    // 设置token信息
    let index = userData.users.findIndex(u => u.email === foundUser.email);
    userData.users[index].token = foundUser.email;
    // 填充响应
    const response = new user.LoginResponse();
    response.setSuccess(true);
    response.setMessage('登录成功');
    response.setToken(foundUser.email);

    const stats = new user.UserStats();
    stats.setEmail(foundUser.email);
    stats.setAvatar(foundUser.avatar);
    stats.setName(foundUser.username);
    stats.setSolvedCount(userStat.solvedCount);
    stats.setTotalProblems(userStat.totalProblems);
    stats.setSolvedProblemsList(userStat.solvedProblems);
    response.setStats(stats);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/user/profile': async (requestData) =>{
    try{
        const request = user.UserStatsSummaryRequest.deserializeBinary(requestData.data);
        // 用email作为token信息,用token信息找到这个用户，
        const token = requestData.headers.Authorization || requestData.headers.authorization;
        const foundUser = users.find(u => u.token === token);
        // 拿到要获取的用户的email
        const email = request.getEmail();
        const response =  new user.UserStatsSummaryResponse();
        const stats = new user.UserStatsSummary();
        const userStat = userStats.find(it => it.email === email);
        if (foundUser.email === email) {
            // 要获取自己的信息页数据
            stats.setSolvedProblems(userStat.solvedProblems.length);
            stats.setAttemptingProblems(userStat.attemptingProblems.length);
            stats.setPublishedBlogs(userStat.publishedBlogs.length);
            stats.setDraftBlogs(userStat.draftBlogs.length);
            stats.setFollowing(userStat.following.length);
            stats.setFollowers(userStat.followers.length);
            stats.setMutualFriends(userStat.mutualFriends.length);
            stats.setBlogLikesNumber(132);
        }else {
            // 查看其他人主页
            stats.setSolvedProblems(userStat.solvedProblems.length);
            // stats.setAttemptingProblems(userStat.attemptingProblems.length);
            stats.setPublishedBlogs(userStat.publishedBlogs.length);
            // stats.setDraftBlogs(userStat.draftBlogs.length);
            stats.setFollowing(userStat.following.length);
            stats.setFollowers(userStat.followers.length);
            // stats.setMutualFriends(userStat.mutualFriends.length);
            stats.setBlogLikesNumber(128);
        }
        response.setStats(stats);
        response.setSuccess(true);
        response.setMessage("获取信息页数据成功");
        return {
            data: response.serializeBinary(),
            status: 200,
            statusText: 'OK',
            headers: {}
        }
    }catch(error) {
        console.error("获取信息页数据失败",error);
        return {
            data: response.serializeBinary(),
            status: 401,
            statusText: 'Not Found',
            headers: {}
        }
    }
  },
  // 用户统计接口
  '/user/stats': async (requestData) => {
    // 确保headers存在
    const request = user.UserStatsRequest.deserializeBinary(requestData.data);
    const headers = requestData.headers || {};
    const token = headers.Authorization || headers.authorization;
    if (!token) {
      const response = new user.UserStatsResponse();
      const stats = new user.UserStats();
      response.setStats(stats);
      response.setSuccess(false);
      response.setMessage("未登录");
      return {
        data: response.serializeBinary(),
        status: 401,
        statusText: 'Unauthorized',
        headers: {}
      };
    }
    const email = request.getEmail();
    if (email !== '' && email !== token) {
        // 用email作为token信息
        const foundUser = users.find(u => u.token === email);
        
        if (!foundUser) {
        const response = new user.UserStatsResponse();
        const stats = new user.UserStats();
        response.setStats(stats);
        response.setSuccess(false);
        response.setMessage("未登录");
        return {
            data: response.serializeBinary(),
            status: 401,
            statusText: 'Not Found',
            headers: {}
        };
        }
        const userStat = userStats.find(it => it.email === foundUser.email);
        if (!userStat) {
        throw new Error('找不到用户统计数据');
        }
        // 找到用户之后，查看用户信息是否是最新的，
        if (request.getVersion() !== "" || request.getVersion() === foundUser.version){
            // 如果请求的版本号不为空且和用户的版本号是相同的，那就是客户端的信息是最新的，不需要获取
            const response = new user.UserStatsResponse();
            response.setVersion(foundUser.version);
            response.setSuccess(true);
            response.setMessage("获取用户统计数据成功");
            return {
                data: response.serializeBinary(),
                status: 200,
                statusText: 'OK',
                headers: {}
            };
        }
        // 如果不是最新的，或者是版本号为空（通过token登录的），那就填充对应的信息，并告知版本号
        const response = new user.UserStatsResponse();
        response.setVersion(foundUser.version);
        const stats = new user.UserStats();
        stats.setEmail(foundUser.email);
        stats.setAvatar(foundUser.avatar);
        stats.setName(foundUser.username);
        stats.setSolvedCount(userStat.solvedCount);
        stats.setTotalProblems(userStat.totalProblems);
        // stats.setSolvedProblemsList(userStat.solvedProblems);
        response.setStats(stats);
        response.setSuccess(true);
        response.setMessage("获取用户统计数据成功");
        return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
        };
    }else {
        // 用email作为token信息
        const foundUser = users.find(u => u.token === token);
        
        if (!foundUser) {
        const response = new user.UserStatsResponse();
        const stats = new user.UserStats();
        response.setStats(stats);
        response.setSuccess(false);
        response.setMessage("未登录");
        return {
            data: response.serializeBinary(),
            status: 401,
            statusText: 'Not Found',
            headers: {}
        };
        }
        const userStat = userStats.find(it => it.email === foundUser.email);
        if (!userStat) {
        throw new Error('找不到用户统计数据');
        }
        // 找到用户之后，查看用户信息是否是最新的，
        if (request.getVersion() !== "" || request.getVersion() === foundUser.version){
            // 如果请求的版本号不为空且和用户的版本号是相同的，那就是客户端的信息是最新的，不需要获取
            const response = new user.UserStatsResponse();
            response.setVersion(foundUser.version);
            response.setSuccess(true);
            response.setMessage("获取用户统计数据成功");
            return {
                data: response.serializeBinary(),
                status: 200,
                statusText: 'OK',
                headers: {}
            };
        }
        // 如果不是最新的，或者是版本号为空（通过token登录的），那就填充对应的信息，并告知版本号
        const response = new user.UserStatsResponse();
        response.setVersion(foundUser.version);
        const stats = new user.UserStats();
        stats.setEmail(foundUser.email);
        stats.setAvatar(foundUser.avatar);
        stats.setName(foundUser.username);
        stats.setSolvedCount(userStat.solvedCount);
        stats.setTotalProblems(userStat.totalProblems);
        stats.setSolvedProblemsList(userStat.solvedProblems);
        response.setStats(stats);
        response.setSuccess(true);
        response.setMessage("获取用户统计数据成功");
        return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
        };
    }
  },

  '/user/register': async (data) => {
    const request = user.RegisterRequest.deserializeBinary(data.data);
    // 验证码检查
    if ("123456" !== request.getCode()) {
      const response = new user.RegisterResponse();
      response.setSuccess(false);
      response.setMessage('验证码错误');
      
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }

    // 检查邮箱是否已注册
    if (userData.users.some(u => u.email === request.getEmail())) {
      const response = new user.RegisterResponse();
      response.setSuccess(false);
      response.setMessage('邮箱已注册');
      
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }

    // 创建新用户
    const newUser = {
      email: request.getEmail(),
      username: request.getUsername(),
      password: request.getPassword(),
      avatar: request.getAvatar(),
      createdAt: new Date().toISOString(),
      token: ''
    };
    const userstat = {
        email: request.getEmail(),
        solvedCount: 0,
        totalProblems: 100,
        solvedProblems: []
    };
    userData.users.push(newUser);
    userStats.push(userstat);

    const response = new user.RegisterResponse();
    response.setSuccess(true);
    response.setMessage('注册成功');
    
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/user/logout': async (requestData) =>{
    const request = user.LogoutRequest.deserializeBinary(requestData.data);
      const token = request.getToken();
    //   用email作为token信息,退出登录的时候，删除token的信息
        let index = userData.users.findIndex(u => u.email === token);
        userData.users[index].token = '';
    
      const response = new user.LogoutResponse();
      response.setSuccess(true);
      response.setMessage("登出成功");
      return {
        data: response.serializeBinary(),
        status: 200,
        statisText: 'OK'
      };
  },

  // 更新用户名
  '/user/update-username': async (requestData) => {
    const token = requestData.headers.Authorization;
    const request = user.UpdateUsernameRequest.deserializeBinary(requestData.data);
    const newUsername = request.getNewUsername();
    
    const { success, message } = await updateUsername(token, newUsername);
    
    const response = new user.UpdateUsernameResponse();
    response.setSuccess(success);
    response.setMessage(message);
    
    return {
      data: response.serializeBinary(),
      status: success ? 200 : 400,
      statusText: success ? 'OK' : 'Bad Request',
      headers: {}
    };
  },

  // 更新头像
  '/user/update-avatar': async (requestData) => {
    const token = requestData.headers.Authorization;
    const request = user.UpdateAvatarRequest.deserializeBinary(requestData.data);
    const avatarData = request.getAvatar();
    
    const { success, message, avatar } = await updateAvatar(token, avatarData);
    
    const response = new user.UpdateAvatarResponse();
    response.setSuccess(success);
    response.setMessage(message);
    if (avatar) {
      response.setAvatar(avatar);
    }
    
    return {
      data: response.serializeBinary(),
      status: success ? 200 : 400,
      statusText: success ? 'OK' : 'Bad Request',
      headers: {}
    };
  },

  // 修改密码
  '/user/change-password': async (requestData) => {
    const token = requestData.headers.Authorization;
    const request = user.ChangePasswordRequest.deserializeBinary(requestData.data);
    const currentPassword = request.getCurrentPassword();
    const newPassword = request.getNewPassword();
    const { success, message } = await changePassword(token, currentPassword, newPassword);
    
    const response = new user.ChangePasswordResponse();
    response.setSuccess(success);
    response.setMessage(message);
    
    return {
      data: response.serializeBinary(),
      status: success ? 200 : 400,
      statusText: success ? 'OK' : 'Bad Request',
      headers: {}
    };
  },

  // 通过邮箱验证码修改密码
  '/user/change-password-by-email': async (requestData) => {
    const token = requestData.headers.Authorization;
    const request = user.ChangePasswordByEmailRequest.deserializeBinary(requestData.data);
    const verificationCode = request.getCode();
    const newPassword = request.getNewPassword();
    const { success, message } = await changePasswordByEmail(token, verificationCode, newPassword);
    
    const response = new user.ChangePasswordResponse();
    response.setSuccess(success);
    response.setMessage(message);
    
    return {
      data: response.serializeBinary(),
      status: success ? 200 : 400,
      statusText: success ? 'OK' : 'Bad Request',
      headers: {}
    };
  },

  '/user/get-follow-status': async (requestData) => {
    const request = user.GetFollowStatusRequest.deserializeBinary(requestData.data);
    const email = request.getEmail();
    const token = request.getToken();
    const response = new user.GetFollowStatusResponse();
    const targetUser = users.find(u => u.email === email);
    if (!targetUser) {
      response.setSuccess(false);
      response.setMessage("用户不存在");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }
    response.setSuccess(true);
    response.setMessage("获取关注状态成功");
    response.setFollowing(targetUser.following.includes(token));
    response.setFollowers(targetUser.followers.includes(token));
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/user/follow': async (requestData) => {
    const request = user.FollowRequest.deserializeBinary(requestData.data);
    const email = request.getEmail();
    const token = request.getToken();
    const targetUser = users.find(u => u.email === email);
    const response = new user.FollowResponse();
    if (!targetUser) {
      response.setSuccess(false);
      response.setMessage("用户不存在");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }
    if (targetUser.following.includes(token)) {
      response.setSuccess(false);
      response.setMessage("已关注");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }
    targetUser.following.push(token);
    targetUser.followers.push(email);
    response.setSuccess(true);
    response.setMessage("关注成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/user/unfollow': async (requestData) => {
    const request = user.UnfollowRequest.deserializeBinary(requestData.data);
    const email = request.getEmail();
    const token = request.getToken();
    const targetUser = users.find(u => u.email === email);
    const response = new user.UnfollowResponse();
    if (!targetUser) {
      response.setSuccess(false);
      response.setMessage("用户不存在");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {} 
      };
    }
    if (!targetUser.following.includes(token)) {
      response.setSuccess(false);
      response.setMessage("未关注");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }
    targetUser.following = targetUser.following.filter(u => u !== token);
    targetUser.followers = targetUser.followers.filter(u => u !== email);
    response.setSuccess(true);
    response.setMessage("取消关注成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/user/get-user-info': async (requestData) => {
    const request = user.GetUserInfoRequest.deserializeBinary(requestData.data);
    const email = request.getEmail();
    const token = request.getToken();
    const response = new user.GetUserInfoResponse();
    const userinfo = users.find(u => u.email === email);
    if (!userinfo) {
      response.setSuccess(false);
      response.setMessage("用户不存在");
      return {
        data: response.serializeBinary(),
        status: 400,
        statusText: 'Bad Request',
        headers: {}
      };
    }
    response.setSuccess(true);
    response.setMessage("获取用户信息成功");
    response.setEmail(userinfo.email);
    response.setAvatar(userinfo.avatar);
    response.setName(userinfo.username);
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/user/get-default-avatar': async (requestData) => {
    const request = user.GetDefaultAvatarRequest.deserializeBinary(requestData.data);
    const response = new user.GetDefaultAvatarResponse();
    response.setSuccess(true);
    response.setMessage("获取默认头像成功");
    response.setAvatarsList([avatar_male, avatar_female]);
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  // 博客相关接口
  '/blog/list': async (config) => {
    const request = blog.BlogListRequest.deserializeBinary(config.data);
    const page = request.getPage();
    const pageSize = request.getPageSize();
    
    const blogData = generateBlogList({ 
      page, 
      pageSize 
    });
    const response = new blog.BlogListResponse();
    response.setBlogsList(blogData.blogs.map(log => {
      const blogProto = new blog.BlogPreview();
      blogProto.setId(log.id);
      blogProto.setTitle(log.title);
      blogProto.setDate(log.date);
      blogProto.setPreview(log.preview);
      blogProto.setLikes(log.likes);
      blogProto.setViewCount(log.view_count);
      const author = new user.UserStats();
      author.setEmail(log.author.email);
      author.setName(log.author.name);
      author.setAvatar(log.author.avatar);
      blogProto.setAuthor(author);
      return blogProto;
    }));
    
    response.setTotal(blogData.total);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/blog/detail': async (requestData) => {
    const request = blog.BlogDetailRequest.deserializeBinary(requestData.data);
    const page = request.getPage();
    const pagesize = request.getPageSize();
    const {log,totalComments} = await getBlogDetail(request.getId(),page,pagesize);
    
    const response = new blog.BlogDetailResponse();
    const blogProto = new blog.BlogDetail();
    blogProto.setId(log.id);
    blogProto.setTitle(log.title);
    blogProto.setContent(log.content);
    blogProto.setDate(log.date);
    blogProto.setLikes(log.likes);
    const author = new user.UserStats()
    author.setEmail(log.author.email);
    author.setAvatar(log.author.avatar);
    author.setName(log.author.name);
    blogProto.setAuthor(author);
    blogProto.setCommentsList(log.comments.map(comm => {
        const ret = new blog.Comment();
        const author = new user.UserStats();
        author.setEmail(comm.author.email);
        author.setName(comm.author.name);
        author.setAvatar(comm.author.avatar)
        ret.setId(comm.id);
        ret.setAuthor(author)
        ret.setContent(comm.content)
        ret.setCreatedAt(comm.created_at);
        ret.setLikes(comm.likes);
        ret.setParentId(comm.parent_id);
        ret.setCommentTotal(comm.comment_total);
        return ret;
    }));
    blogProto.setCommentTotal(totalComments);
    
    response.setBlog(blogProto);
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/blog/like': async (requestData) => {
    const request = blog.LikeRequest.deserializeBinary(requestData.data);
    const result = await submitLike(request.getBlogId());
    
    const response = new blog.LikeResponse();
    response.setSuccess(result.success);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/blog/submitcomment': async (requestData) => {
    const request = blog.CommentRequest.deserializeBinary(requestData.data);
    const result = await submitComment(request.getBlogId(), request.getContent());
    
    const response = new blog.CommentResponse();
    response.setSuccess(result.success);
    response.setMessage(result.message);
    const comment = new blog.Comment();
    comment.setId(result.comment.id);
    comment.setContent(result.comment.content);
    const author = new user.UserStats();
    author.setEmail(result.comment.author.email);
    author.setName(result.comment.author.name);
    author.setAvatar(result.comment.author.avatar);
    comment.setAuthor(author);
    comment.setCreatedAt(result.comment.created_at);
    comment.setLikes(result.comment.likes);
    comment.setParentId(result.comment.parent_id);
    response.setComment(comment);


    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
//   获取评论列表
    '/blog/getcomments': async (requestData) => {
      const request = blog.BlogCommentRequest.deserializeBinary(requestData.data);
      const blogId = request.getBlogId();
      const parentId = request.getParentId();
      const page = request.getPage();
      const pageSize = request.getPageSize();
      const response = new blog.BlogCommentResponse();
      const {list, total} = await getSubComments(blogId, parentId, page, pageSize);
      list.forEach(item => {
        const comment = new blog.Comment();
        comment.setId(item.id);
        comment.setContent(item.content);
        const author = new user.UserStats();
        author.setEmail(item.author.email);
        author.setName(item.author.name);
        author.setAvatar(item.author.avatar);
        comment.setAuthor(author);
        comment.setCreatedAt(item.created_at);
        comment.setLikes(item.likes);
        comment.setParentId(item.parent_id);
        comment.setCommentTotal(item.comment_total);
        response.addComments(comment);
      });
      response.setSuccess(true);
      response.setTotal(total);
        return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
        };
    },
    // /blog/userblogs
    '/blog/userblogs': async (requestData) => {
        const request = blog.UserBlogListRequest.deserializeBinary(requestData.data);
        const token = request.getToken();
        const email = request.getEmail();
        const published = request.getPublished();
        const page = request.getPage();
        const pageSize = request.getPageSize();

        const blogData = generateBlogList({ 
            page, 
            pageSize 
          });
          const response = new blog.BlogListResponse();
          blogData.blogs.forEach(log => {
            if (log.author.email !== email) {
              return;
            }
            const blogProto = new blog.BlogPreview();
            blogProto.setId(log.id);
            blogProto.setTitle(log.title);
            blogProto.setDate(log.date);
            blogProto.setPreview(log.preview);
            blogProto.setLikes(log.likes);
            blogProto.setViewCount(log.view_count);
            const author = new user.UserStats();
            author.setEmail(log.author.email);
            author.setName(log.author.name);
            author.setAvatar(log.author.avatar);
            blogProto.setAuthor(author);
            response.addBlogs(blogProto);
          });
          
          response.setTotal(blogData.total);
          return {
            data: response.serializeBinary(),
            status: 200,
            statusText: 'OK',
            headers: {}
          };
    },
    '/blog/delete': async (requestData) => {
      const request = blog.DeleteBlogRequest.deserializeBinary(requestData.data);
    //   const result = await deleteBlog(request.getBlogId());
      const response = new blog.DeleteBlogResponse();
      response.setSuccess(true);
      response.setMessage("删除成功");
    //   response.setSuccess(false);
    //   response.setMessage("删除失败");
      return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
      };
    },
    '/blog/create': async (requestData) => {
      const request = blog.CreateBlogRequest.deserializeBinary(requestData.data);
    //   const result = await createBlog(request.getTitle(), request.getContent(), request.getPublished());
      console.log(request.toObject())
      const response = new blog.CreateBlogResponse();
      response.setSuccess(true);
      response.setMessage("创建成功");
      return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
      };
    },
    '/blog/edit': async (requestData) => {
      const request = blog.EditBlogRequest.deserializeBinary(requestData.data);
    //   const result = await editBlog(request.getBlogId());
      const blogId = request.getBlogId();
      const log = findBlogById(blogId);
      console.log(request.toObject())
      const response = new blog.EditBlogResponse();
      if (!log) {
        response.setSuccess(false);
        response.setMessage("博客不存在");
        return {
          data: response.serializeBinary(),
          status: 200,
          statusText: 'OK',
          headers: {}
        };
      }
      response.setSuccess(true);
      response.setMessage("请求成功");
      response.setBlogId(log.id);
      response.setTitle(log.title);
      response.setContent(log.content);
      response.setPublished(log.published);
      return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
      };
    },
    // /blog/likedblogs
    '/blog/likedblogs': async (requestData) => {
      const request = blog.LikedBlogListRequest.deserializeBinary(requestData.data);
      const email = request.getEmail();
      const page = request.getPage();
      const pageSize = request.getPageSize();
      const blogData = generateBlogList({ 
        page, 
        pageSize 
      });
      const response = new blog.LikedBlogListResponse();
      response.setBlogsList(blogData.blogs.map(log => {
        const blogProto = new blog.BlogPreview();
        blogProto.setId(log.id);
        blogProto.setTitle(log.title);
        blogProto.setDate(log.date);
        blogProto.setPreview(log.preview);
        blogProto.setLikes(log.likes);
        blogProto.setViewCount(log.view_count);
        const author = new user.UserStats();
        author.setEmail(log.author.email);
        author.setName(log.author.name);
        author.setAvatar(log.author.avatar);
        blogProto.setAuthor(author);
        return blogProto;
      }));
      response.setTotal(blogData.total);
      return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
      };
    },
    '/blog/deletelike': async (requestData) => {
      const request = blog.DeleteLikeBlogRequest.deserializeBinary(requestData.data);
    //   const result = await deleteLikeBlog(request.getBlogId());
      const response = new blog.DeleteLikeBlogResponse();
      response.setSuccess(true);
      response.setMessage("取消点赞成功");
      return {
        data: response.serializeBinary(),
        status: 200,
        statusText: 'OK',
        headers: {}
      };
    },
  // 题目相关接口
  '/problem/list': async (config) => {
    const request = problem.ProblemListRequest.deserializeBinary(config.data);
    const page = request.getPage();
    const pageSize = request.getPagesize();
    const difficulty = request.getDifficulty();
    const solvedStatus = request.getSolvedstatus();
    const sortBy = request.getSortby();
    const search = request.getSearchquery();

    // 从headers获取token并查询email
    let email = '';
    const token = config.headers?.Authorization || config.headers?.authorization;
    if (token) {
      const foundUser = users.find(u => u.token === token);
      if (foundUser) {
        email = foundUser.email;
      }
    }

    
    const { problems, total} = generateProblemList(
      email, // 传递查询到的email
      solvedStatus, // 使用新的通过状态筛选
      page,
      pageSize,
      sortBy,
      difficulty
    );
    
    const response = new problem.ProblemListResponse();
    response.setProblemsList(problems);
    response.setTotal(total);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/problem/detail': async (config) => {
    const request = problem.ProblemDetailRequest.deserializeBinary(config.data);
    const id = request.getId();
    if (!id) throw new Error('缺少题目ID参数');
    
    const p = generateProblemDetail(id);
    if (!p) throw new Error('题目不存在');

    const response = new problem.ProblemDetailResponse();
    response.setProblem(p);

    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  '/problem/submit': async (requestData) => {
    const request = problem.SubmitRequest.deserializeBinary(requestData.data);
    const response = new problem.SubmitResponse();

    if (request.getSubmit() == true) {
      // 提交代码
      if (request.getCode().length % 2 == 1){
        // 模拟通过
        response.setAccepted(true);
        response.setTimeCost(0.78);
        response.setMemoryCost(1.1);
        response.setCode(request.getCode());
        response.setLanguage(request.getLanguage());
      }else {
        // 模拟不通过
        response.setAccepted(false);
        response.setMessage("提交未通过");
      }
    }else {
      // 自测运行
      response.setMessage("代码输出：" + request.getTestData());
    }
  
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  // 新增提交记录接口
  '/problem/submissionlist': async (config) => {
    const request = problem.SubmissionListRequest.deserializeBinary(config.data);
    const page = request.getPage();
    const pagesize = request.getPageSize();
    
    const response = new problem.SubmissionListResponse();
    const {list, total} = getSubmissions(page, pagesize);
    response.setResultList(list);
    response.setTotal(total); // 模拟总提交数
    
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  //
  '/problem/submissiondetail': async (config) => {
    const request = problem.SubmissionDetailRequest.deserializeBinary(config.data);
    const id = request.getId();
    const response = new problem.SubmitResponse();
    const result = getSubmissionsDetail(id);
    response.setAccepted(result.accepted);
    response.setTimeCost(result.time_cost);
    response.setMemoryCost(result.memory_cost);
    response.setCode(result.code);
    response.setLanguage(result.language);
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
//   聊天相关的接口
  '/chat/get_sessions': async (requestData) => {
    const request = chat.GetSessionsRequest.deserializeBinary(requestData.data);
    const page = request.getPage();
    const pageSize = request.getPageSize();
    const {sessions, total} = await getSessions(page, pageSize);
    const response = new chat.GetSessionsResponse();
    sessions.forEach(session => {
      const sessionProto = new chat.Session();
      sessionProto.setId(session.id);
      sessionProto.setName(session.name);
      sessionProto.setAvatar(session.avatar);
      sessionProto.setIsGroup(session.is_group);
      sessionProto.setIsPinned(session.is_pinned);
      sessionProto.setLastReadMessageId(session.last_read_message_id);
      sessionProto.setUpdatedAt(session.updated_at);
      response.addSessions(sessionProto);
    });
    response.setTotal(total);
    response.setSuccess(true);
    response.setMessage("请求成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/chat/get_session_messages': async (requestData) => {
    const request = chat.GetSessionMessagesRequest.deserializeBinary(requestData.data);
    const sessionId = request.getSessionId();
    const page = request.getPage();
    const pageSize = request.getPageSize();
    const {messages, total} = await getSessionMessages(sessionId, page, pageSize);
    const response = new chat.GetSessionMessagesResponse();
    messages.forEach(message => {
      const messageProto = new chat.Message();
      messageProto.setMessageId(message.id);
      messageProto.setSessionId(message.session_id);
      messageProto.setFromId(message.from_id);
      messageProto.setSendAt(message.send_at);
      messageProto.setType(message.type);
      if (message.type === 'text') {
        messageProto.setText(message.text);
      } else if (message.type === 'image') {
        const imageProto = new chat.ImageInfo();
        imageProto.setId(message.image.id);
        imageProto.setPath(message.image.path);
        messageProto.setImage(imageProto);
      } else if (message.type === 'file') {
        const fileProto = new chat.FileInfo();
        fileProto.setId(message.file.id);
        fileProto.setName(message.file.name);
        fileProto.setSize(message.file.size);
        messageProto.setFile(fileProto);
      }
      response.addMessages(messageProto);
    });
    response.setTotal(total);
    response.setSuccess(true);
    response.setMessage("请求成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/chat/get_friends': async (requestData) => {
    const request = chat.GetFriendsRequest.deserializeBinary(requestData.data);
    const ids = request.getUserIdsList();
    const {users} = await getFriends(ids);
    const response = new chat.UsersResponse();
    users.forEach(user => {
      const userProto = new chat.User();
      userProto.setId(user.id);
      userProto.setName(user.name);
      userProto.setEmail(user.email);
      userProto.setAvatar(user.avatar);
      response.addUser(userProto);  
    });
    response.setTotal(users.length);
    response.setSuccess(true);
    response.setMessage("请求成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  '/chat/get-followers': async (requestData) => {
     const request = chat.GetFollowersRequest.deserializeBinary(requestData.data);
     const email = request.getEmail();
     const page = request.getPage();
     const pageSize = request.getPageSize();
     
     // 模拟关注者数据 - 返回部分用户作为关注者
     const followers = users.slice(1, 6); // 取5个用户作为关注者
     const startIndex = (page - 1) * pageSize;
     const endIndex = Math.min(startIndex + pageSize, followers.length);
     const paginatedFollowers = followers.slice(startIndex, endIndex);
     
     const response = new chat.UsersResponse();
     paginatedFollowers.forEach(user => {
       response.addUserIds(user.email); // 使用email作为用户ID
     });
     response.setTotal(followers.length);
     response.setSuccess(true);
     response.setMessage("获取关注者列表成功");
     return {
       data: response.serializeBinary(),
       status: 200,
       statusText: 'OK',
       headers: {}
     };
   },
  '/chat/get-following': async (requestData) => {
     const request = chat.GetFollowingRequest.deserializeBinary(requestData.data);
     const email = request.getEmail();
     const page = request.getPage();
     const pageSize = request.getPageSize();
     
     // 模拟关注的用户数据
     const following = users.slice(2, 8); // 取6个用户作为关注的用户
     const startIndex = (page - 1) * pageSize;
     const endIndex = Math.min(startIndex + pageSize, following.length);
     const paginatedFollowing = following.slice(startIndex, endIndex);
     
     const response = new chat.UsersResponse();
     paginatedFollowing.forEach(user => {
       response.addUserIds(user.email); // 使用email作为用户ID
     });
     response.setTotal(following.length);
     response.setSuccess(true);
     response.setMessage("获取关注列表成功");
     return {
       data: response.serializeBinary(),
       status: 200,
       statusText: 'OK',
       headers: {}
     };
   },
  '/chat/get-mutual-followers': async (requestData) => {
     const request = chat.GetMutualFollowersRequest.deserializeBinary(requestData.data);
     const page = request.getPage();
     const pageSize = request.getPageSize();
     
     // 模拟互相关注的用户数据
     const mutualFollowers = users.slice(3, 6); // 取3个用户作为互相关注的用户
     const startIndex = (page - 1) * pageSize;
     const endIndex = Math.min(startIndex + pageSize, mutualFollowers.length);
     const paginatedMutual = mutualFollowers.slice(startIndex, endIndex);
     
     const response = new chat.UsersResponse();
     paginatedMutual.forEach(user => {
       response.addUserIds(user.email); // 使用email作为用户ID
     });
     response.setTotal(mutualFollowers.length);
     response.setSuccess(true);
     response.setMessage("获取互相关注列表成功");
     return {
       data: response.serializeBinary(),
       status: 200,
       statusText: 'OK',
       headers: {}
     };
   },
  '/chat/add_favorite': async (requestData) => {
    const request = chat.AddFavoriteRequest.deserializeBinary(requestData.data);
    const path = request.getImagePath();
    console.log('path', path)
    const response = new chat.AddFavoriteResponse();
    response.setSuccess(true);
    response.setMessage("添加收藏表情成功");
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
  
  // 获取或创建私聊会话
  '/chat/get_or_create_private_session': async (requestData) => {
    const request = chat.GetOrCreatePrivateSessionRequest.deserializeBinary(requestData.data);
    const token = request.getToken();
    const targetEmail = request.getTargetEmail();
    const sessionId = userSessionMap[targetEmail];
    // 获取sessioninfo
    const sessionInfo = StaticSessions.find(session => session.id === sessionId);
    // 创建响应
    const response = new chat.GetOrCreatePrivateSessionResponse();
    response.setSuccess(true);
    response.setMessage( '私聊会话获取成功');
    response.setSessionId(sessionId);
    response.setIsNew(false);
    const session = new chat.Session();
    session.setId(sessionId);
    session.setName(sessionInfo.name);
    session.setAvatar(sessionInfo.avatar);
    session.setLastReadMessageId(sessionInfo.last_read_message_id);
    session.setUpdatedAt(sessionInfo.updated_at);
    session.setIsPinned(sessionInfo.is_pinned);

    response.setSessionInfo(session);
    
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },

  // 搜索接口
  '/home/search': async (requestData) => {
    const request = home.SearchRequest.deserializeBinary(requestData.data);
    const type = request.getType();
    const page = request.getPage() || 1;
    const pageSize = request.getPageSize() || 20;
    
    const response = new home.SearchResponse();
    response.setSuccess(true);
    response.setMessage('搜索成功');
    
    // 分页计算
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    
    if (type === 'problems') {
      // 返回固定的题目列表
      const { problems: allProblems } = generateProblemList('', 0, 1, 200);
      const paginatedResults = allProblems.slice(start, end);
      
      response.setProblemsList(paginatedResults);
      response.setBlogsList([]);
      response.setUsersList([]);
      response.setTotal(allProblems.length);
      
    } else if (type === 'blogs') {
      // 返回固定的博客列表
      const allBlogs = generateBlogList({ page: 1, pageSize: 200 }).blogs;
      const paginatedResults = allBlogs.slice(start, end);
      
      // 转换为 protobuf 格式
      const blogProtos = paginatedResults.map(log => {
        const blogProto = new blog.BlogPreview();
        blogProto.setId(log.id);
        blogProto.setTitle(log.title);
        blogProto.setDate(log.date);
        blogProto.setPreview(log.preview);
        blogProto.setLikes(log.likes);
        blogProto.setViewCount(log.view_count);
        const author = new user.UserStats();
        author.setEmail(log.author.email);
        author.setName(log.author.name);
        author.setAvatar(log.author.avatar);
        blogProto.setAuthor(author);
        return blogProto;
      });
      
      response.setProblemsList([]);
      response.setBlogsList(blogProtos);
      response.setUsersList([]);
      response.setTotal(allBlogs.length);
      
    } else if (type === 'users') {
      // 返回固定的用户列表
      const paginatedResults = users.slice(start, end);
      
      // 转换为UserStats格式
      const userStats = paginatedResults.map(u => {
        const userStat = new user.UserStats();
        userStat.setEmail(u.email);
        userStat.setAvatar(u.avatar);
        userStat.setName(u.username);
        return userStat;
      });
      
      response.setProblemsList([]);
      response.setBlogsList([]);
      response.setUsersList(userStats);
      response.setTotal(users.length);
      
    } else {
      // 未知搜索类型
      response.setSuccess(false);
      response.setMessage(`不支持的搜索类型: ${type}`);
      response.setProblemsList([]);
      response.setBlogsList([]);
      response.setUsersList([]);
      response.setTotal(0);
    }
    
    return {
      data: response.serializeBinary(),
      status: 200,
      statusText: 'OK',
      headers: {}
    };
  },
};

export const getMockData = async (url, requestData) => {
  if (!mockResponses[url]) throw new Error(`未定义的模拟接口: ${url}`);
  return await mockResponses[url](requestData);
};
